# -*- coding: utf-8 -*-
# @author: HRUN
from rest_framework.exceptions import APIException

from rest_framework.views import exception_handler

from django.http import JsonResponse
from django.db.models import ProtectedError

class CustomException(APIException):
    status_code = 500
    default_detail = '删除失败，请检查相关引用!'
    default_code = 'invalid'


def globalExceptionHandler(exc, context):
    # 调用默认的异常处理器
    response = exception_handler(exc, context)

    # 处理级联删除时ProtectedError错误统一报错
    if isinstance(exc, ProtectedError):
        return JsonResponse({'message': '该数据存在被其他数据引用或包含其他被引用数据，请删除后再试！'}, status=400)

    if response is not None:
        # 处理序列化器逻辑校验错误
        if 'non_field_errors' in response.data:
            response.data = {'message': response.data['non_field_errors'][0]}
        # 处理数据库字段校验错误
        else:
            error_messages = []
            for key, errors in response.data.items():
                if isinstance(errors, list):
                    for error in errors:
                        error_messages.append(f"{key}{error}")
                elif isinstance(errors, str):
                    error_messages.append(f"{errors}")
                    # response.status_code = 400


            response.data = {'message': " ".join(error_messages).replace("。", "! ")}

    return response
